const { ErrorModel } = require("../model/resModel");
const JWT = require("../utils/jwt_util");
const regToken = /Bearer (.+)/i;

module.exports = async (ctx, next) => {
    console.log("loginCheck ctx",ctx);
    console.log("loginCheck beforeHandle ctx.session", ctx.session);

    const token = ctx.headers["authorization"]
        ? regToken.exec(ctx.headers["authorization"])[1]
        : "";
    const payload = JWT.verify(token);

    console.log("loginCheck token=", token);
    console.log("loginCheck payload=", payload);

    // 看看session中有无username
    // 登录成功时会在session中写入username
    console.log("loginCheck ctx.session", ctx.session);
    console.log("loginCheck payload.username", payload.username);

    if(payload.username){
        await next();
        return
    }

    // if (
    //     ctx.session.username &&
    //     payload.username &&
    //     payload.username === ctx.session.username
    // ) {
    //     // 下一环
    //     await next();
    //     return;
    // }

    // session中没有登录信息 直接返回结果
    ctx.body = new ErrorModel(null, "未登录", ErrorModel.Errors.LoginRequired);
};
